package com.xmy.cultivate.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.constants.MqConstants;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.respons.ResStudentAccount;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.service.IStudentNewsService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 学生所在班级与课程（分班表） 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-09-25
 */
@RestController
@RequestMapping("/api/studentGrade")
public class StudentGradeController extends BaseController {

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    IRenewDataService iRenewDataService;

    @Autowired
    @Lazy
    ITeacherContinueInfoService iTeacherContinueInfoService;

    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
    @Lazy
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    IStudentGradeTemporaryService studentGradeTemporaryService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    IRecordCourseService iRecordCourseService;

    @Autowired
    ILackCourseLogService iLackCourseLogService;

    @Autowired
    IStudentNewsService iStudentNewsService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IStudentGradeContinueService iStudentGradeContinueService;


    @GetMapping()
    public Result findAll(@RequestParam Map reMap, String[] subjectsList, String[] schoolList) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));

        IPage<Grade> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();

        //String subjectsId = (String) reMap.get("subjectsId");
        String shiftDateStart = (String) reMap.get("shiftDateStart");
        String shiftDateEnd = (String) reMap.get("shiftDateEnd");
        String courseId = (String) reMap.get("courseId");
        String readingStatus = (String) reMap.get("readingStatus");
        String name = (String) reMap.get("name");

        if (schoolList.length > 0) {
            queryWrapper.in("a.school_id", schoolList);
        } else {
            queryWrapper.in("a.school_id", this.baseSchoolIdList);
        }

        if (subjectsList.length > 0) {
            queryWrapper.in("a.subjects_id", subjectsList);
        }
        queryWrapper.eq("a.deleted", 0);
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);
        queryWrapper.inSql(StringUtils.isNotBlank(readingStatus), "reading_status", readingStatus);

        if (StringUtils.isNotBlank(shiftDateStart) && StringUtils.isNotBlank(shiftDateEnd)) {
            queryWrapper.between("created_at", shiftDateStart, shiftDateEnd);
        }

        queryWrapper.like(StringUtils.isNotBlank(name), "c.name", name);

        if (this.sourseLeve.equals(2)) {
            queryWrapper.eq("b.teacher_id", this.adminId);
        }

        iStudentGradeService.findAll(iPage, queryWrapper);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 分班
     *
     * @return
     */
    @PostMapping("/divideClasses")
    public Result divideClasses(@RequestBody Map reMap) {

        //System.out.print("orderDetailId:"+reMap.get("orderDetailId").toString());

        Long orderDetailId = Long.parseLong(reMap.get("orderDetailId").toString());
        Long gradeId = Long.parseLong(reMap.get("gradeId").toString());

        // 获取原本班级在读学生数量
        Grade grade = iGradeService.getById(gradeId);
        if (grade.getFullCount() != null && grade.getFullCount() > 0 && (grade.getLessonType() == 2 || grade.getLessonType() == 3)) {
            Integer studyCount = iStudentGradeService.getGradeStudyCount(gradeId);
            if (studyCount >= grade.getFullCount()) {
                return new Result(Code.ERROR, "", "班级满班人数为："+grade.getFullCount()+",已满班，不能再继续添加学员");
            }
        }


        OrderDetail orderDetail = iOrderDetailService.getById(orderDetailId);

        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);

        Quarter quarter = iQuarterService.getQuarterForYearAndNum(grade.getYearPart(),grade.getQuarterNum());

        if (this.isSuper != 1) {
            //学期班
            if (quarter.getType().equals(1)) {
                //非周末
                if (!grade.getWeekDates().equals("6") && !grade.getWeekDates().equals("0")) {
                    String planGradeName = iStudentGradeService.getWeekDatesPlanGrade(grade.getYearPart(), grade.getQuarterNum(), orderDetail.getStudentId(), grade.getWeekDates());
                    if (StringUtils.isNotBlank(planGradeName)) {
                        return new Result(Code.ERROR, "", CommonUtil.getWeekForId(Integer.parseInt(grade.getWeekDates())) + "已排：" + planGradeName + ",添加失败");
                    }
                } else {
                    //周末
                    List<String> stringList = new ArrayList<>();
                    String clashStr = "";
                    List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingClash(orderDetail.getYearPart(), orderDetail.getQuarterNum(), orderDetail.getStudentId(), gradeId, nowDateTime.toString());
                    if (repairCourseList.size() > 0) {
                        Student student = iStudentService.getById(orderDetail.getStudentId());
                        for (RepairCourse repairCourse : repairCourseList) {
                            clashStr = student.getName() + "," + repairCourse.getGradeName() + "" + repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart() + " " + repairCourse.getTimeEnd();
                            stringList.add(clashStr);
                        }
                    }
                    if (stringList.size() > 0) {
                        StringBuilder studentBuilder = new StringBuilder();
                        studentBuilder.append("存在时间冲突:" + String.join(",", stringList));
                        return new Result(Code.ERROR, stringList, studentBuilder.toString());
                    }
                }
            } else {
                //假期班
                List<String> stringList = new ArrayList<>();
                String clashStr = "";
                List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingClash(orderDetail.getYearPart(), orderDetail.getQuarterNum(), orderDetail.getStudentId(), gradeId, nowDateTime.toString());
                if (repairCourseList.size() > 0) {
                    Student student = iStudentService.getById(orderDetail.getStudentId());
                    for (RepairCourse repairCourse : repairCourseList) {
                        clashStr = student.getName() + "," + repairCourse.getGradeName() + "" + repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart() + " " + repairCourse.getTimeEnd();
                        stringList.add(clashStr);
                    }
                }
                if (stringList.size() > 0) {
                    StringBuilder studentBuilder = new StringBuilder();
                    studentBuilder.append("存在时间冲突:" + String.join(",", stringList));
                    return new Result(Code.ERROR, stringList, studentBuilder.toString());
                }
            }
        }

        Result rs = iStudentGradeService.divideClasses(orderDetailId, gradeId);


        // 判断是否在新生表
        QueryWrapper<StudentNews> studentNewsQueryWrapper = new QueryWrapper<>();
        studentNewsQueryWrapper.eq("student_id", orderDetail.getStudentId());
        studentNewsQueryWrapper.eq("year_part", grade.getYearPart());
        studentNewsQueryWrapper.eq("quarter_num", grade.getQuarterNum());
        studentNewsQueryWrapper.eq("subjects_id", grade.getSubjectsId());
        studentNewsQueryWrapper.last("limit 1");
        StudentNews studentNews = iStudentNewsService.getOne(studentNewsQueryWrapper);
        if (studentNews != null) {
            if (quarter.getType() == 1) {
//                if (studentNews.getIsAddLack() == 1) {
                    // 添加所有的缺课
                    iCourseSchedulingDetailService.resumeClassesLackCourse(grade.getId(), orderDetail.getStudentId(), 6, null,1);
//                } else {
//                    // 添加created_at时间之后的排课缺课
//                    LocalDateTime createdAt = studentNews.getCreatedAt();
//                    iCourseSchedulingDetailService.resumeClassesLackCourse(grade.getId(), orderDetail.getStudentId(), 6, String.valueOf(createdAt));
//
//                }
            } else {
                // 假期班，添加所有的缺课
                iCourseSchedulingDetailService.resumeClassesLackCourse(grade.getId(), orderDetail.getStudentId(), 6, null,1);
            }
        }


        return rs;
    }

    /**
     * 调班
     *
     * @return
     */
    @PostMapping("/melodyClass")
    public Result melodyClass(@RequestBody StudentGrade studentGrade) {
        studentGrade.setAdminId(this.adminId);
        Result rs = iStudentGradeService.melodyClass(studentGrade);
        try {
            if (rs.getCode().equals(Code.OK)) {
                Grade grade = iGradeService.getById(studentGrade.getInGradeId());
                Integer count = studentGrade.getStudentIdList().length;
                // 获取原本班级在读学生数量
                if (grade.getFullCount() != null && grade.getFullCount() > 0 && (grade.getLessonType() == 2 || grade.getLessonType() == 3)) {
                    Integer studyCount = iStudentGradeService.getGradeStudyCount(grade.getId());
                    if (studyCount + count > grade.getFullCount()) {
                        return new Result(Code.ERROR, "", "已超出班级人数上限，无法继续添加学员");
                    }
                }

                Course course = iCourseService.getById(grade.getCourseId());
                for (String studentId : studentGrade.getStudentIdList()) {
                    if (grade.getLessonType().equals(1)) {//同步帐号信息到其它系统
                        iMqPushService.updateStudentAccount(grade.getYearPart(), grade.getQuarterNum(), Long.parseLong(studentId), course.getSubjectsId());
                        //智能课、刷题班分班
                        StudentGrade studentGradeAllot = new StudentGrade();
                        studentGradeAllot.setYearPart(grade.getYearPart());
                        studentGradeAllot.setQuarterNum(grade.getQuarterNum());
                        studentGradeAllot.setSchoolId(grade.getSchoolId());
                        studentGradeAllot.setGradeId(grade.getId());
                        studentGradeAllot.setStudentId(Long.parseLong(studentId));
                        studentGradeAllot.setSubjectsId(course.getSubjectsId());
                        studentGradeAllot.setLessonType(grade.getLessonType());
                        iMqPushService.autoAllotStudentGrade(studentGradeAllot);
                    }
                }
            }
        } catch (Exception e) {

        }

        return rs;
    }


    @RequiresPermissions(value = "grade:detail:del")
    @DeleteMapping("/{studentId}/{gradeId}")
    public Result delete(@PathVariable(value = "studentId") Long studentId, @PathVariable(value = "gradeId") Long gradeId) {

        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("student_id", studentId);
        studentGradeQueryWrapper.eq("grade_id", gradeId);
        studentGradeQueryWrapper.eq("status", 1);
        studentGradeQueryWrapper.in("reading_status", 0, 1);
        studentGradeQueryWrapper.eq("deleted", 0);


        Grade grade = iGradeService.getById(gradeId);
        Course course = iCourseService.getById(grade.getCourseId());

        Long count = iStudentGradeService.count(studentGradeQueryWrapper);

        Integer courseType = iRecordCourseService.getRecordCourseByDate(course.getSubjectsId(), studentId);
        if (courseType != 0) {
            return new Result(Code.ERROR, "", "该学员还有调未上，不能删除,如要删除，请先删除已安排的调课");
        }

        boolean rs = false;
        if (count == 0) {
            return new Result(Code.ERROR, "", "数据不存在");
        } else if (count == 1) {
            StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
            if (studentGrade == null) {
                return new Result(Code.ERROR, "", "数据不存在");
            }
            if (studentGrade.getUseCourseCount() > 0) {
                return new Result(Code.ERROR, "", "已扣过课时，不能删除");
            }
            iTeacherContinueInfoService.remove(new QueryWrapper<TeacherContinueInfo>().eq("student_grade_id", studentGrade.getId()));
            rs = iStudentGradeService.remove(studentGradeQueryWrapper);
            iStudentGradeContinueService.changeEndDate(studentGrade);//删除，续报调整截止日期

        } else if (count > 1) {
            List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
            Integer delCount = 0;
            StudentGrade  delStudentGrade = null;
            for (StudentGrade studentGrade : studentGradeList) {
                if (studentGrade.getUseCourseCount() == 0) {
                    delStudentGrade = studentGrade;
                    iStudentGradeService.removeById(studentGrade);
                    //更新为最后一条
                    //iStudentGradeService.updateIsLast(studentGrade.getYearPart(), studentGrade.getQuarterNum(), studentId, studentGrade.getSubjectsId(), studentGrade.getLessonType());
                    iMqPushService.updateStudentGradeLast(studentGrade.getYearPart(), studentGrade.getQuarterNum(), studentId, studentGrade.getSubjectsId(), studentGrade.getLessonType());
                    rs = true;
                    delCount++;
                }
            }
            if (studentGradeList.size() == delCount) {
                if (Objects.isNull(delStudentGrade)){
                    iStudentGradeContinueService.changeEndDate(delStudentGrade);//删除，续报调整截止日期
                }
            }
        }

        QueryWrapper<LackCourseLog> lackCourseLogQueryWrapper = new QueryWrapper<>();
        lackCourseLogQueryWrapper.eq("student_id", studentId);
        lackCourseLogQueryWrapper.eq("grade_id", grade.getId());
        lackCourseLogQueryWrapper.ne("is_repair", 1);
        iLackCourseLogService.remove(lackCourseLogQueryWrapper);

        iRenewDataService.deleteTeacherForGradeDelStudent(grade, grade.getTeacherId(), studentId, course.getSubjectsId(), grade.getYearPart(), course.getQuarterNum());

        if (grade.getLessonType().equals(1)) {
            // 查询删除后是否有其他分班
            QueryWrapper<StudentGrade> wrapper = new QueryWrapper<>();
            wrapper.eq("student_id", studentId);
            wrapper.ne("status", 3);
            wrapper.eq("lesson_type", grade.getLessonType());
            wrapper.eq("deleted", 0);
            wrapper.eq("year_part", grade.getYearPart());
            wrapper.eq("quarter_num", grade.getQuarterNum());
            wrapper.eq("subjects_id", course.getSubjectsId());
            long studentCount = iStudentGradeService.count(wrapper);
            ResStudentAccount resStudentAccount = new ResStudentAccount();
            try {
                if (studentCount > 0) {
                    iMqPushService.updateStudentAccount(grade.getYearPart(), grade.getQuarterNum(), studentId, course.getSubjectsId());
                } else {
                    resStudentAccount.setStudentId(studentId);
                    resStudentAccount.setQuarterNum(grade.getQuarterNum());
                    resStudentAccount.setYearPart(grade.getYearPart());
                    resStudentAccount.setSubjectsId(course.getSubjectsId());
                    iMqPushService.delStudentGradeUpdateAccount(resStudentAccount);
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        return new Result(rs ? Code.OK : Code.ERROR);
    }

    @RequiresPermissions(value = "grade:detail:batch")
    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody StudentGrade studentGradeParam) {
        Long gradeId = studentGradeParam.getGradeId();
        List<String> rightAdd = new ArrayList<>();
        List<String> errorAdd = new ArrayList<>();

        for (Object studentIdObj : studentGradeParam.getStudentIdList()) {
            Long studentId = Long.parseLong(studentIdObj.toString());

            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("student_id", studentId);
            studentGradeQueryWrapper.eq("grade_id", gradeId);
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("use_course_count", 0);//使用课时为0的都能删除
            //studentGradeQueryWrapper.in("reading_status", 0,1);
            studentGradeQueryWrapper.eq("deleted", 0);
            Student student = iStudentService.getById(studentId);

            Grade grade = iGradeService.getById(gradeId);
            Course course = iCourseService.getById(grade.getCourseId());

            Long count = iStudentGradeService.count(studentGradeQueryWrapper);
            boolean rs = false;
            if (count == 0) {
                errorAdd.add(student.getName() + ":删除失败");
                continue;
            } else if (count == 1) {
                StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                if (studentGrade == null) {
                    errorAdd.add(student.getName() + ":删除失败");
                    continue;
                }
                if (studentGrade.getUseCourseCount() > 0) {
                    errorAdd.add(student.getName() + ":扣过课时不能删除");
                    continue;
                }
                iTeacherContinueInfoService.remove(new QueryWrapper<TeacherContinueInfo>().eq("student_grade_id", studentGrade.getId()));
                rs = iStudentGradeService.remove(studentGradeQueryWrapper);
                iStudentGradeContinueService.changeEndDate(studentGrade);//删除，续报调整截止日期
            } else if (count > 1) {
                Integer delCount = 0;
                List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
                StudentGrade delStudentGrade = null;
                for (StudentGrade studentGrade : studentGradeList) {
                    if (studentGrade.getUseCourseCount() == 0) {
                        delStudentGrade = studentGrade;
                        iStudentGradeService.removeById(studentGrade);
                        //iStudentGradeService.updateIsLast(studentGrade.getYearPart(), studentGrade.getQuarterNum(), studentId, studentGrade.getSubjectsId(),studentGrade.getLessonType());
                        iMqPushService.updateStudentGradeLast(studentGrade.getYearPart(), studentGrade.getQuarterNum(), studentId, studentGrade.getSubjectsId(), studentGrade.getLessonType());
                        rs = true;
                        delCount++;
                    }
                }
                if (studentGradeList.size() == delCount) {
                    if (Objects.isNull(delStudentGrade)){
                        iStudentGradeContinueService.changeEndDate(delStudentGrade);//删除，续报调整截止日期
                    }
                }
            }
            rightAdd.add(student.getName() + ":删除成功");
            iRenewDataService.deleteTeacherForGradeDelStudent(grade, grade.getTeacherId(), studentId, course.getSubjectsId(), grade.getYearPart(), course.getQuarterNum());
            QueryWrapper<LackCourseLog> lackCourseLogQueryWrapper = new QueryWrapper<>();

            lackCourseLogQueryWrapper.eq("student_id", studentId);
            lackCourseLogQueryWrapper.eq("grade_id", grade.getId());
            lackCourseLogQueryWrapper.ne("is_repair", 1);
            iLackCourseLogService.remove(lackCourseLogQueryWrapper);


            if (grade.getLessonType().equals(1)) {
                // 查询删除后是否有其他分班
                QueryWrapper<StudentGrade> wrapper = new QueryWrapper<>();
                wrapper.eq("student_id", studentId);
                wrapper.ne("status", 3);
                wrapper.eq("lesson_type", grade.getLessonType());
                wrapper.eq("deleted", 0);
                wrapper.eq("year_part", grade.getYearPart());
                wrapper.eq("quarter_num", grade.getQuarterNum());
                wrapper.eq("subjects_id", course.getSubjectsId());
                long studentCount = iStudentGradeService.count(wrapper);
                ResStudentAccount resStudentAccount = new ResStudentAccount();
                try {
                    if (studentCount > 0) {
                        iMqPushService.updateStudentAccount(grade.getYearPart(), grade.getQuarterNum(), studentId, course.getSubjectsId());
                    } else {
                        resStudentAccount.setStudentId(studentId);
                        resStudentAccount.setQuarterNum(grade.getQuarterNum());
                        resStudentAccount.setYearPart(grade.getYearPart());
                        resStudentAccount.setSubjectsId(course.getSubjectsId());
                        iMqPushService.delStudentGradeUpdateAccount(resStudentAccount);
                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }
        return new Result(Code.OK, "", String.join(",", rightAdd) + String.join(",", errorAdd));
    }


    /**
     * 班级里结课
     *
     * @return
     */
    @PutMapping("/finishGrade")
    public Result finishGrade(@RequestBody StudentGrade studentGrade) {
        boolean rs = iStudentGradeService.finishCourse(studentGrade);

        Grade grade = iGradeService.getById(studentGrade.getGradeId());
        Course course = iCourseService.getById(grade.getCourseId());
        iMqPushService.updateStudentAccount(grade.getYearPart(), grade.getQuarterNum(), studentGrade.getStudentId(), course.getSubjectsId());

        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "结课失败");
    }

    @PutMapping("/studentFixed")
    public Result studentFixed(@RequestBody StudentGrade studentGrade) {
        iStudentGradeService.studentFixed(studentGrade);
        return new Result(Code.OK, "", "");
    }

    @PutMapping("/studentFixedCancel")
    public Result studentFixedCancel(@RequestBody StudentGrade studentGrade) {
        iStudentGradeService.studentFixedCancel(studentGrade);
        return new Result(Code.OK, "", "");
    }


    /**
     * 班级里停课
     *
     * @return
     */
    @PutMapping("/stopGrade")
    public Result stopGrade(@RequestBody StudentGrade studentGrade) {
        boolean rs = iStudentGradeService.stopGrade(studentGrade);

        Grade grade = iGradeService.getById(studentGrade.getGradeId());
        Course course = iCourseService.getById(grade.getCourseId());
        iMqPushService.updateStudentAccount(grade.getYearPart(), grade.getQuarterNum(), studentGrade.getStudentId(), course.getSubjectsId());

        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "停课失败");
    }

    /**
     * 课时状态修改
     *
     * @return
     */
    @PutMapping("/courseStatusChange")
    public Result courseStatusChange(@RequestBody StudentGrade studentGrade) {
        boolean rs = iStudentGradeService.courseStatusChange(studentGrade);
        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "失败");
    }


    /**
     * 班级里复课
     *
     * @return
     */
    @PutMapping("/agrainGrade")
    public Result agrainGrade(@RequestBody StudentGrade studentGrade) {
        boolean rs = iStudentGradeService.agrainGrade(studentGrade);
        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "复课失败");
    }

    /**
     * 学员档案里结课
     *
     * @return
     */
    @PutMapping("/finishGradeForOrder")
    public Result finishGradeForOrder(@RequestBody StudentGrade studentGrade) {
        boolean rs = iStudentGradeService.finishCourseForOrder(studentGrade);
        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "结课失败");
    }

    /**
     * 学员档案里停课
     *
     * @return
     */
    @PutMapping("/stopGradeForOrder")
    public Result stopGradeForOrder(@RequestBody StudentGrade studentGrade) {
        boolean rs = iStudentGradeService.stopGradeForOrder(studentGrade);

        StudentGrade studentGrade1 = iStudentGradeService.getOne(new QueryWrapper<StudentGrade>().eq("order_detail_id", studentGrade.getOrderDetailId()).last("LIMIT 1"));
        Grade grade = iGradeService.getById(studentGrade1.getGradeId());
        Course course = iCourseService.getById(grade.getCourseId());
        iMqPushService.updateStudentAccount(grade.getYearPart(), grade.getQuarterNum(), studentGrade.getStudentId(), course.getSubjectsId());

        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "停课失败");
    }

    /**
     * 班级复课
     *
     * @return
     */
    @PutMapping("/agrainGradeForOrder")
    public Result agrainGradeForOrder(@RequestBody StudentGrade studentGrade) {
        boolean rs = iStudentGradeService.agrainGradeForOrder(studentGrade);

        Grade grade = new Grade();
        if (studentGrade.getOrderDetailId() != null) {
            StudentGrade studentGrade1 = iStudentGradeService.getOne(new QueryWrapper<StudentGrade>().eq("order_detail_id", studentGrade.getOrderDetailId()).eq("status", 1).last("LIMIT 1"));
            grade = iGradeService.getById(studentGrade1.getGradeId());
            Course course = iCourseService.getById(grade.getCourseId());
            iMqPushService.updateStudentAccount(grade.getYearPart(), grade.getQuarterNum(), studentGrade.getStudentId(), course.getSubjectsId());
        } else if (studentGrade.getGradeId() != null) {
            grade = iGradeService.getById(studentGrade.getGradeId());
        }

        // 判断是否在新生表
        QueryWrapper<StudentNews> studentNewsQueryWrapper = new QueryWrapper<>();
        studentNewsQueryWrapper.eq("student_id", studentGrade.getStudentId());
        studentNewsQueryWrapper.eq("year_part", grade.getYearPart());
        studentNewsQueryWrapper.eq("quarter_num", grade.getQuarterNum());
        studentNewsQueryWrapper.eq("subjects_id", grade.getSubjectsId());
        studentNewsQueryWrapper.last("limit 1");
        StudentNews studentNews = iStudentNewsService.getOne(studentNewsQueryWrapper);
        if (studentNews != null) {
            Quarter quarter = iQuarterService.getQuarterForYearAndNum(grade.getYearPart(), grade.getQuarterNum());
            if (quarter.getType() == 1) {
//                if (studentNews.getIsAddLack() == 1) {
                    // 添加所有的缺课
                    iCourseSchedulingDetailService.resumeClassesLackCourse(grade.getId(), studentGrade.getStudentId(), 6, null,2);
//                } else {
//                    // 添加created_at时间之后的排课缺课
//                    LocalDateTime createdAt = studentNews.getCreatedAt();
//                    iCourseSchedulingDetailService.resumeClassesLackCourse(grade.getId(), studentGrade.getStudentId(), 6, String.valueOf(createdAt));
//                }
            } else {
                // 假期班，添加所有的缺课
                iCourseSchedulingDetailService.resumeClassesLackCourse(grade.getId(), studentGrade.getStudentId(), 6, null,2);
            }
        } else {
            if (grade.getLessonType().equals(1)) {
                // 复课后缺课
                iCourseSchedulingDetailService.resumeClassesLackCourse(grade.getId(), studentGrade.getStudentId(), 6, null,2);
            }
        }

        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "复课失败");
    }

    /**
     * 班级批量复课
     *
     * @return
     */
    @PostMapping("/agrainGradeBatchForOrder")
    public Result agrainGradeBatchForOrder(@RequestBody StudentGrade studentGrade) {
        boolean rs = iStudentGradeService.agrainBatchGradeForOrder(studentGrade);

        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "复课失败");
    }

    @PutMapping("/isCheckHouse")
    @ApiOperation("批量核对")
    public Result isCheckHouse(@RequestBody Map reMap) {
        List<Object> checkList = (List<Object>) reMap.get("checkList");
        String gradeId = (String) reMap.get("gradeId");
        for (Object object : checkList) {
            String jsonObject = JSON.toJSONString(object);
            StudentGrade studentGrade = JSONObject.parseObject(jsonObject, StudentGrade.class);
            iStudentGradeService.updateIsCheckHouse(gradeId, String.valueOf(studentGrade.getStudentId()));
        }
        return new Result(Code.UPDATE_OK, Code.UPDATE_OK_MSG, "批量核对成功~");
    }

    @GetMapping("/updateStudentIsPresort")
    public Result updateStudentIsPresort() {
        iStudentGradeService.updateStudentIsPresort();
        return new Result(Code.OK, "", "成功~");
    }


    /**
     * 班级添加临时学员
     *
     * @return
     */
    @PostMapping("addGradeStudentTemporary")
    public Result addGradeStudentTemporary(@RequestBody Map reMap) {
        String gradeId = (String) reMap.get("gradeId");
        String schoolDate = (String) reMap.get("schoolDate");
        List<Object> studentIdList = (List<Object>) reMap.get("studentIdList");

        // 查询对应的排课详情id
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("grade_id", gradeId);
        wrapper.eq("school_date", schoolDate);
        CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getOne(wrapper);
        if (Objects.nonNull(courseSchedulingDetail) && courseSchedulingDetail.getDeleted() == 1) {
            wrapper.clear();
            wrapper.eq("pid", courseSchedulingDetail.getId());
            courseSchedulingDetail = iCourseSchedulingDetailService.getOne(wrapper);
        } else {
            //添加排课详情


        }

        // 添加临时学员到表中
        for (Object object : studentIdList) {
            String jsonObject = JSON.toJSONString(object);
            StudentGradeTemporary studentGradeTemporary = JSONObject.parseObject(jsonObject, StudentGradeTemporary.class);
            studentGradeTemporary.setGradeId(Long.parseLong(gradeId));
            studentGradeTemporary.setSchedulingDetailId(courseSchedulingDetail.getId());
            studentGradeTemporary.setType(0);
            studentGradeTemporaryService.save(studentGradeTemporary);
        }

        return new Result(Code.OK, "", "添加成功");
    }

}
